package org.loofer.ext.utils.security;

public class CRC64 {
    private static final long INITIALCRC = -1;
    private static final long POLY64REV = -7661587058870466123L;
    private static long[] sCrcTable = new long[256];

    static {
        for (int i = 0; i < 256; i++) {
            long part = (long) i;
            for (int j = 0; j < 8; j++) {
                part = (part >> 1) ^ ((((int) part) & 1) != 0 ? POLY64REV : 0);
            }
            sCrcTable[i] = part;
        }
    }

    private CRC64() {
    }

    public static long getValue(byte[] buffer) {
        long crc = -1;
        for (byte aBuffer : buffer) {
            crc = sCrcTable[(((int) crc) ^ aBuffer) & 255] ^ (crc >> 8);
        }
        return crc;
    }

    public static long getValue(String in) {
        if (in == null || in.length() == 0) {
            return 0;
        }
        return getValue(getBytes(in));
    }

    private static byte[] getBytes(String in) {
        byte[] result = new byte[(in.length() * 2)];
        int output = 0;
        for (char ch : in.toCharArray()) {
            int i = output + 1;
            result[output] = (byte) (ch & 255);
            output = i + 1;
            result[i] = (byte) (ch >> 8);
        }
        return result;
    }
}
